import Vue from 'vue';
import { K_USER_TOKEN, K_TOKEN_EXPIRE, IS_PROD } from '@/shared/consts';

const expose = {
  get payServer() {
    const { protocol, host } = window.location
    return true ? 'http://www.tssdeyy.com/hesuan' : `${protocol}//${host}`
  },
  get apiServer() {
    // #ifdef H5
    const { protocol, host } = window.location
    // return IS_PROD ? `${protocol}//${host}` : '/api'
    return IS_PROD ? `http://hs.tssdeyy.com` : '/api'
    // #endif

    // #ifndef H5
    return IS_PROD ? 'http://localhost.mhugh.net:9207' : 'http://localhost.mhugh.net:9207'
    // #endif
  },
  
  http: Vue.prototype.$http = (opt, withAuth=true) => {
    const { url, success, header } = opt
    let userToken
    if (withAuth) {
      let app = getApp()
      userToken = !!app ? app.globalData.userToken : uni.getStorageSync(K_USER_TOKEN)
    }

    if (!opt.method || opt.method.toUpperCase() == 'GET') {
      if (!opt.data) {
        opt.data = {}
      }
      opt.data.ts = new Date().getTime()
    }
    
    return uni.request(Object.assign(opt, {
      url: `${expose.apiServer}${url}`,
      header: (withAuth && !!userToken ? Object.assign(header || {}, {
        'Authorization': `Bearer ${userToken}`,
        'Accept-Language': 'zh-CN,zh;q=0.9',
      }) : header),
      success: (res) => {
        success(res.data, res)
      },
	  
    }))
  },
}

Vue.prototype.$upload = (opt, withAuth=true) => {
  const { url, success, header } = opt
  let userToken
  if (withAuth) {
    let app = getApp()
    userToken = !!app ? app.globalData.userToken : uni.getStorageSync(K_USER_TOKEN)
  }
  
  return uni.uploadFile(Object.assign(opt, {
    url: `${expose.apiServer}${url}`,
    header: (withAuth && !!userToken ? Object.assign(header || {}, {
      'Authorization': `Bearer ${userToken}`
    }) : header),
    success: (res) => {
      success(res.data)
    },
  }))
}

module.exports = expose